using System;
using MediaPortal.GUI.Library;
using System.Text.RegularExpressions;
using System.Net;
using System.Text;
using System.ComponentModel;
using MediaPortal.Player;
using System.Collections.Generic;
//using MediaPortal.Utils.Services;
using MediaPortal.Dialogs;
//using Rss;
using MediaPortal.GUI.View;
using ITMSClient;
using HDTrailerPlugin;



namespace OnlineVideos
{
	public class ItunesTrailerUtil : SiteUtilBase
	{
		public override string getSiteId()
		{
			return "15";
		}
		public override bool hasMultipleVideos()
		{
			return true;
		}
		public override List<GUIOnlineVideos.VideoInfo> getVideoList(String fsUrl)
		{
            try{
			List<GUIOnlineVideos.VideoInfo> loListItems = new List<GUIOnlineVideos.VideoInfo>();
			if(fsUrl.StartsWith("%")){
				if(fsUrl.Length == 1){
					loListItems = getAllTrailers();
					loListItems.Sort(delegate(GUIOnlineVideos.VideoInfo v1, GUIOnlineVideos.VideoInfo v2) { return v1.Title.CompareTo(v2.Title); });
				}else{
					fsUrl = fsUrl.Substring(1);
					loListItems = search(fsUrl);
				}
			}else{
				DownloadTrailers(fsUrl);

				foreach (ITMSClient.TrailerInfo trailer in HDTrailerPlugin.AppleTrailers.trailers)
				{
					loListItems.Add(loadVideoInfo(trailer));
				}
			}
			return loListItems;
            }catch (Exception e)
            {
                Log.Error(e);
                throw e;
            }

		}
		public override List<OnlineVideos.GUIOnlineVideos.VideoInfo> getOtherVideoList(OnlineVideos.GUIOnlineVideos.VideoInfo video)
		{
			List<OnlineVideos.GUIOnlineVideos.VideoInfo> videoList = new List<OnlineVideos.GUIOnlineVideos.VideoInfo>();
			TrailerInfo trailer = (TrailerInfo)video.Other;
			trailer = AppleTrailers.GetTrailerUrls(trailer);
			GUIOnlineVideos.VideoInfo newVideo;
			foreach (String name in trailer.trailers.Keys){				
				newVideo = loadVideoInfo(trailer);
				newVideo.Title2 = name;
				newVideo.VideoUrl = trailer.trailers[name];
                Log.Info("added video url={0}", newVideo.VideoUrl);
				videoList.Add(newVideo);
			}
			return videoList;
		}
		public override String getUrl(GUIOnlineVideos.VideoInfo video,GUIOnlineVideos.SiteSettings foSite)
		{
			if(video.VideoUrl.EndsWith(".mov")){
				return video.VideoUrl;
			}
			return getTrailerUrl(video);
		}
		private String getTrailerUrl(GUIOnlineVideos.VideoInfo video){
			TrailerInfo trailer = (TrailerInfo)video.Other;
            Log.Info("requesting to get url for " + video.VideoUrl);
            trailer.Url = new Uri("http://movies.apple.com" + video.VideoUrl);
            Log.Info("Trailer quality set to {0}", OnlineVideoSettings.getInstance().AppleTrailerSize);
            trailer = AppleTrailers.ProcessTrailer(trailer,OnlineVideoSettings.getInstance().AppleTrailerSize);
            
			return trailer.TrailerStreamCollection[0].Uri.ToString();
		}
		public List<GUIOnlineVideos.VideoInfo> getAllTrailers(){
			
			Dictionary<string, GUIOnlineVideos.RssLink> loRssList= OnlineVideoSettings.getInstance().moSiteList[getSiteId()].RssList;
			List<GUIOnlineVideos.VideoInfo> loListItems = new List<GUIOnlineVideos.VideoInfo>();
			foreach(GUIOnlineVideos.RssLink link in loRssList.Values){
				
				if(link.url.StartsWith("%")){
					continue;
				}
			
				
				DownloadTrailers(link.url);
				Dictionary<string, string> loTrailersFound = new Dictionary<string,string>();
				foreach (ITMSClient.TrailerInfo trailer in HDTrailerPlugin.AppleTrailers.trailers)
				{
					
					if(loTrailersFound.ContainsKey(trailer.Title) == false){
						loTrailersFound.Add(trailer.Title.ToUpper(), "");
						
						//loItem.Length = trailer..
						loListItems.Add(loadVideoInfo(trailer));
					}
					
				}
				
				
			}
			return loListItems;

		}
		private List<GUIOnlineVideos.VideoInfo> search(String fsQuery){
			fsQuery = fsQuery.ToUpper();
			
			List<GUIOnlineVideos.VideoInfo>loAllTrailers = getAllTrailers();
			List<GUIOnlineVideos.VideoInfo>loSearchResult = loAllTrailers.FindAll(delegate(GUIOnlineVideos.VideoInfo v1) { return v1.Title.ToUpper().Contains(fsQuery);});
			
			return loSearchResult;
		}
		private void DownloadTrailers(String fsLink){
            try
            {
                //Log.Info("getting trailers from url:"+fsLink.url);
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += new DoWorkEventHandler(HDTrailerPlugin.AppleTrailers.GetAppleTrailersRSS);
                AppleTrailers._workerCompleted = false;

                worker.RunWorkerAsync(fsLink);
                DateTime startTime = DateTime.Now;
                TimeSpan duration = new TimeSpan();
                //using (WaitCursor cursor = new WaitCursor())
                {

                    while (HDTrailerPlugin.AppleTrailers._workerCompleted == false && duration.TotalSeconds < 10)
                    {
                        //Log.Info("donwload trailer duration = {0} seconds",duration.TotalSeconds);
                        //GUIWindowManager.Process();
                        duration = DateTime.Now - startTime; ;

                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw e;
            }
			
			//Log.Info("finished getting trailers from url:"+fsLink.url);
		}
		private GUIOnlineVideos.VideoInfo loadVideoInfo(TrailerInfo trailer){
            try
            {
                GUIOnlineVideos.VideoInfo newVideo = new GUIOnlineVideos.VideoInfo();
                newVideo.Title = trailer.Title;
                newVideo.VideoUrl = trailer.Title;
                newVideo.Description = trailer.Overview;
                if (trailer.PosterUrl != null)
                {
                    newVideo.ImageUrl = trailer.PosterUrl.ToString();
                }
                newVideo.Other = trailer;
                return newVideo;
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw e;
            }
			
		}
        public override bool hasNextPage()
        {
            if (AppleTrailers.currentPage == null || AppleTrailers.currentPage.NextPageUri == null)
            {
                //Log.Info("current page is null or next page uri is null");
                return false;
            }
            //Log.Info("{0}",AppleTrailers.currentPage.NextPageUri);
            Log.Info(AppleTrailers.currentPage.NextPageUri.ToString());
            return String.IsNullOrEmpty(AppleTrailers.currentPage.NextPageUri.ToString()) == false;
        }
        public override List<GUIOnlineVideos.VideoInfo> getNextPageVideos()
        {
            List<GUIOnlineVideos.VideoInfo> trailerList = new List<GUIOnlineVideos.VideoInfo>();
            if (hasNextPage())
            {
                trailerList = getVideoList(AppleTrailers.currentPage.NextPageUri.ToString());
            }
            return trailerList;
        }
        public override List<GUIOnlineVideos.VideoInfo> getPreviousPageVideos()
        {
            List<GUIOnlineVideos.VideoInfo> trailerList = new List<GUIOnlineVideos.VideoInfo>();
            if (hasPreviousPage())
            {
                trailerList = getVideoList(AppleTrailers.currentPage.BackPageUri.ToString());
            }
            return trailerList;
           
        }
        public override bool hasPreviousPage()
        {
            if (AppleTrailers.currentPage == null || AppleTrailers.currentPage.BackPageUri == null)
            {
                return false;
            }
            return String.IsNullOrEmpty(AppleTrailers.currentPage.BackPageUri.ToString()) == false;
        }
		public override void AddFavorite(OnlineVideos.GUIOnlineVideos.VideoInfo foVideo, string fsSiteId)
		{				
			foVideo.VideoUrl = getTrailerUrl(foVideo);
			//TrailerInfo info = (TrailerInfo)foVideo.Other;
			foVideo.Title += " - "+foVideo.Title2;
			
			base.AddFavorite(foVideo, fsSiteId);
		}
	}
}
